<template>
  <div>
    <n-space justify="space-between" style="margin-bottom:12px">
      <n-input v-model:value="q" placeholder="搜索任务名称..." clearable style="max-width:260px" @input="filterTasks" />
      <n-button type="primary" @click="openCreate">新建任务</n-button>
    </n-space>
    <n-data-table :columns="columns" :data="filteredRows" :bordered="false" :single-line="false" :loading="loading" />

    <n-drawer v-model:show="show" width="520" placement="right">
      <n-drawer-content :title="isEdit ? '编辑任务' : '新建任务'">
        <task-editor :model="model" @saved="onSaved" />
      </n-drawer-content>
    </n-drawer>

    <n-modal v-model:show="dlqShow" preset="card" title="死信队列" style="width:800px">
      <DLQViewer :task-id="dlqTaskId" />
    </n-modal>

    <n-modal v-model:show="logsShow" preset="card" title="消息日志" style="width:1000px">
      <LogsViewer :task-id="logsTaskId" />
    </n-modal>
  </div>
</template>
<script setup lang="ts">
import { h, onMounted, ref, computed } from 'vue'
import axios from 'axios'
import { NButton, NSpace, NInput, NDataTable, NDrawer, NDrawerContent, NModal, NIcon, NTooltip, useMessage, NTag } from 'naive-ui'
import { WarningOutline } from '@vicons/ionicons5'
import TaskEditor from '../widgets/TaskEditor.vue'
import DLQViewer from '../widgets/DLQViewer.vue'
import LogsViewer from '../widgets/LogsViewer.vue'

const message = useMessage()
const show = ref(false)
const isEdit = ref(false)
const loading = ref(false)
const model = ref<any>({ direction: 'KAFKA_TO_RABBIT', enabled: true })
const q = ref('')
const rows = ref<any[]>([])
const dlqShow = ref(false)
const dlqTaskId = ref<number | null>(null)
const logsShow = ref(false)
const logsTaskId = ref<number | null>(null)

const columns = [
  { title: '名称', key: 'name', render: (row:any) => row.name },
  { title: '方向', key: 'direction', render: (row:any) => h(NTag, {
    type: row.direction==='KAFKA_TO_RABBIT'?'info':'success'
  }, {
    default: () => row.direction.replace('KAFKA_TO_RABBIT', 'Kafka → RabbitMQ').replace('RABBIT_TO_KAFKA', 'RabbitMQ → Kafka')
  }) },
  { title: '状态', key: 'status', render: (row:any) => h('div', { style: 'display:flex;align-items:center;gap:8px' }, [
    h(NTag, {
      type: row.status==='RUNNING'?'success':(row.status==='STOPPING'?'warning':(row.status==='ERROR'?'error':'default'))
    }, {
      default: () => row.status
    }),
    row.lastErrorMsg ? h(NTooltip, {}, {
      trigger: () => h(NIcon, { size: 16, color: '#f56565', style: 'cursor:pointer' }, { default: () => h(WarningOutline) }),
      default: () => row.lastErrorMsg
    }) : null
  ]) },
  { title: '统计', key: 'stats', render: (row:any) => h('div', { style: 'font-size:12px;color:#888' }, [
    `处理: ${row.processed || 0}`,
    h('br'),
    `失败: ${row.failed || 0}`
  ]) },
  { title: '操作', key: 'actions', render: (row:any) => h('div', { style: 'display:flex;gap:4px;flex-wrap:wrap' }, [
      h(NButton, { size:'small', type:'primary', onClick: () => start(row.id), disabled: row.status==='RUNNING' || row.status==='STOPPING' }, { default: () => '启动' }),
      h(NButton, { size:'small', onClick: () => stop(row.id), disabled: row.status!=='RUNNING' }, { default: () => '停止' }),
      h(NButton, { size:'small', onClick: () => restart(row.id), disabled: row.status==='STOPPING' }, { default: () => '重启' }),
      h(NButton, { size:'small', type:'info', ghost:true, onClick: () => edit(row), disabled: row.status==='RUNNING' || row.status==='STOPPING' }, { default: () => '编辑' }),
      h(NButton, { size:'small', type:'warning', ghost:true, onClick: () => viewLogs(row.id) }, { default: () => '日志' }),
      h(NButton, { size:'small', type:'warning', ghost:true, onClick: () => viewDLQ(row.id) }, { default: () => '死信' }),
      (row.failed && row.failed > 0) ? h(NButton, { size:'small', type:'success', ghost:true, onClick: () => clearError(row.id) }, { default: () => '清错' }) : null,
      h(NButton, { size:'small', type:'error', ghost:true, onClick: () => remove(row.id), disabled: row.status==='RUNNING' || row.status==='STOPPING' }, { default: () => '删除' })
    ].filter(Boolean)) }
]

const filteredRows = computed(() => {
  if (!q.value) return rows.value
  return rows.value.filter((x:any) => x.name.toLowerCase().includes(q.value.toLowerCase()))
})

const load = async () => {
  loading.value = true
  try {
    const { data } = await axios.get('/api/tasks')
    rows.value = data
  } catch (e) {
    message.error('加载任务失败')
    console.error(e)
  } finally {
    loading.value = false
  }
}

function filterTasks() {
  // 触发计算属性更新
}

onMounted(load)

function openCreate() {
  isEdit.value = false
  model.value = {
    direction: 'KAFKA_TO_RABBIT',
    enabled: true,
    concurrency: 1,
    maxRetries: 3,
    retryBackoffMs: 1000
  }
  show.value = true
}

function edit(row:any) {
  isEdit.value = true
  model.value = { ...row }
  show.value = true
}

async function onSaved() {
  show.value = false
  await load()
  message.success('已保存')
}

async function start(id:number) {
  try {
    await axios.post(`/api/tasks/${id}/start`)
    // 等待一下让状态更新
    setTimeout(async () => {
      await load()
    }, 500)
    message.success('已启动')
  } catch (e) {
    message.error('启动失败')
    await load()
  }
}

async function stop(id:number) {
  try {
    await axios.post(`/api/tasks/${id}/stop`)
    message.success('停止中...')

    // 立即刷新一次显示"停止中"状态
    await load()

    // 然后定期检查直到真正停止
    let attempts = 0
    const checkStatus = async () => {
      if (attempts >= 10) return // 最多检查10次

      await load()
      const task = rows.value.find(t => t.id === id)
      if (task && task.status === 'STOPPED') {
        message.success('已停止')
        return
      }

      attempts++
      setTimeout(checkStatus, 1000) // 每秒检查一次
    }

    setTimeout(checkStatus, 1000)
  } catch (e) {
    message.error('停止失败')
    await load()
  }
}

async function restart(id:number) {
  try {
    await axios.post(`/api/tasks/${id}/restart`)
    // 等待一下让状态更新
    setTimeout(async () => {
      await load()
    }, 1000)
    message.success('已重启')
  } catch (e) {
    message.error('重启失败')
    await load()
  }
}

async function remove(id:number) {
  try {
    await axios.delete(`/api/tasks/${id}`)
    await load()
    message.success('已删除')
  } catch (e) {
    message.error('删除失败')
  }
}

function viewDLQ(taskId: number) {
  dlqTaskId.value = taskId
  dlqShow.value = true
}

function viewLogs(taskId: number) {
  logsTaskId.value = taskId
  logsShow.value = true
}

async function clearError(taskId: number) {
  try {
    await axios.post(`/api/tasks/${taskId}/clear-error`)
    await load()
    message.success('已清空错误信息')
  } catch (e) {
    message.error('清空失败')
  }
}
</script>

